// , { constantRoutes, asyncRoutes }
import router from '@/router/index.js'
import store from '@/store/index.js'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = ['404', '/login']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  // 判断是否登录
  if (store.getters.token) {
    // 判断用户信息是否有
    if (!store.getters.userId) {
      // 简化版本的权限控制
      /* / // 1.获取菜单控制的标识
      const { roles: { menus }} = await store.dispatch('user/getUserInfo')
      console.log('menus', menus)
      // 2.过滤动态路由
      const filterRouters = asyncRoutes.filter(t => menus.includes(t.name))
      // 3.添加动态路由
      // 注意:addRoutes不会影响初始化路由配置,也就是说,router.options.routes不会跟着变
      router.addRoutes([...filterRouters, { path: '*', redirect: '/404', hidden: true }])
      // 4.解决菜单没变化的问题
      router.options.routes = [...constantRoutes, ...filterRouters]
      // 5.解决404问题
      return next(to.path)
       */
      // 标准版写法
      // 1.获取菜单控制的标识
      const { roles: { menus }} = await store.dispatch('user/getUserInfo')
      // console.log('menus', menus)
      // 2.过滤动态路由
      const filterRouters = await store.dispatch('permission/filterRoutes', menus)
      // 3.添加动态路由
      router.addRoutes([...filterRouters, { path: '*', redirect: '404', hidden: true }])
      // 解决404问题
      return next(to.path)
    }
    // 是否去登陆页面
    // if (to.path === '/login') {
    //   next('/')
    // } else {
    //   next()
    // }
    to.path === '/login' ? next('/') : next()
  } else {
    // if (whiteList.includes(to.path)) {
    //   next()
    // } else {
    //   // 是否在白名单
    //   if (whiteList.includes(to.path)) {
    //     return next()
    //   }
    //   next('/login')
    // }
    whiteList.includes(to.path) ? next() : next('/login')
  }
  nprogress.done()
})

// 后置守卫
router.afterEach(() => {
  nprogress.done()
})
